export interface MerchantCallback {
  id: string
  orderId: string
  orderType: 'payment' | 'refund'
  merchantId: string
  merchantName: string
  callbackUrl: string
  callbackType: 'webhook' | 'http_post'
  status: 'pending' | 'success' | 'failed' | 'timeout'
  requestHeaders: string
  requestBody: string
  responseBody?: string
  responseCode?: number
  responseHeaders?: string
  retryCount: number
  maxRetryCount: number
  createTime: string
  updateTime: string
  callbackTime?: string
  nextRetryTime?: string
  errorMessage?: string
  remark?: string
}

// 生成指定范围内的随机数
const getRandomNumber = (min: number, max: number) => {
  return Math.floor(Math.random() * (max - min + 1)) + min
}

// 生成模拟数据
export const generateMockData = (count: number = 45): MerchantCallback[] => {
  const data: MerchantCallback[] = []
  const statuses: MerchantCallback['status'][] = ['pending', 'success', 'failed', 'timeout']
  const orderTypes: MerchantCallback['orderType'][] = ['payment', 'refund']
  const callbackTypes: MerchantCallback['callbackType'][] = ['webhook', 'http_post']

  // 添加一些示例数据
  data.push(
    {
      id: 'MC202506031200001',
      orderId: 'P202506031200001',
      orderType: 'payment',
      merchantId: 'M2025060311001',
      merchantName: '测试商户01',
      callbackUrl: 'https://merchant01.example.com/callback/payment',
      callbackType: 'webhook',
      status: 'success',
      requestHeaders: JSON.stringify({
        'Content-Type': 'application/json',
        'X-Signature': 'sha256=abc123...',
        'User-Agent': 'AnyPay-Webhook/1.0'
      }, null, 2),
      requestBody: JSON.stringify({
        orderId: 'P202506031200001',
        merchantId: 'M2025060311001',
        amount: 100.00,
        status: 'success',
        transactionId: '2025060312000000001',
        paymentMethod: 'alipay',
        timestamp: '2025-06-03T12:00:30Z',
        signature: 'sha256_signature_here'
      }, null, 2),
      responseBody: JSON.stringify({
        code: 200,
        message: 'success',
        received: true
      }, null, 2),
      responseCode: 200,
      responseHeaders: JSON.stringify({
        'Content-Type': 'application/json',
        'Server': 'nginx/1.18.0'
      }, null, 2),
      retryCount: 0,
      maxRetryCount: 5,
      createTime: '2025/6/3 12:00:30',
      updateTime: '2025/6/3 12:00:31',
      callbackTime: '2025/6/3 12:00:31',
      remark: '支付成功回调'
    },
    {
      id: 'MC202506031200002',
      orderId: 'R202506031200001',
      orderType: 'refund',
      merchantId: 'M2025060311001',
      merchantName: '测试商户01',
      callbackUrl: 'https://merchant01.example.com/callback/refund',
      callbackType: 'http_post',
      status: 'failed',
      requestHeaders: JSON.stringify({
        'Content-Type': 'application/json',
        'X-Signature': 'sha256=def456...',
        'User-Agent': 'AnyPay-Callback/1.0'
      }, null, 2),
      requestBody: JSON.stringify({
        orderId: 'R202506031200001',
        merchantId: 'M2025060311001',
        refundAmount: 50.00,
        status: 'success',
        refundTransactionId: '2025060312000000101',
        paymentMethod: 'alipay',
        timestamp: '2025-06-03T12:31:00Z',
        signature: 'sha256_signature_here'
      }, null, 2),
      responseCode: 500,
      responseHeaders: JSON.stringify({
        'Content-Type': 'text/html',
        'Server': 'Apache/2.4.41'
      }, null, 2),
      retryCount: 3,
      maxRetryCount: 5,
      createTime: '2025/6/3 12:31:00',
      updateTime: '2025/6/3 12:31:45',
      callbackTime: '2025/6/3 12:31:45',
      nextRetryTime: '2025/6/3 12:36:45',
      errorMessage: '商户服务器内部错误',
      remark: '退款成功回调失败'
    }
  )

  // 生成更多模拟数据
  for (let i = 3; i <= count; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)]
    const orderType = orderTypes[Math.floor(Math.random() * orderTypes.length)]
    const callbackType = callbackTypes[Math.floor(Math.random() * callbackTypes.length)]
    const retryCount = status === 'success' ? 0 : getRandomNumber(0, 5)
    const createdTime = new Date(2025, 5, getRandomNumber(1, 30), getRandomNumber(0, 23), getRandomNumber(0, 59))
    const updatedTime = new Date(createdTime.getTime() + getRandomNumber(0, 3600000)) // 最多1小时后更新

    const orderPrefix = orderType === 'payment' ? 'P' : 'R'
    const orderId = `${orderPrefix}${createdTime.getFullYear()}${String(createdTime.getMonth() + 1).padStart(2, '0')}${String(createdTime.getDate()).padStart(2, '0')}${String(i).padStart(6, '0')}`
    const merchantId = `M${createdTime.getFullYear()}${String(createdTime.getMonth() + 1).padStart(2, '0')}${String(createdTime.getDate()).padStart(2, '0')}${String(getRandomNumber(1000, 9999))}`

    const requestData = orderType === 'payment'
      ? {
          orderId,
          merchantId,
          amount: getRandomNumber(100, 10000) / 100,
          status: 'success',
          transactionId: `${createdTime.getFullYear()}${String(createdTime.getMonth() + 1).padStart(2, '0')}${String(createdTime.getDate()).padStart(2, '0')}${String(getRandomNumber(100000000, 999999999))}`,
          paymentMethod: ['alipay', 'wechat', 'bank'][Math.floor(Math.random() * 3)],
          timestamp: createdTime.toISOString(),
          signature: 'sha256_signature_here'
        }
      : {
          orderId,
          merchantId,
          refundAmount: getRandomNumber(50, 1000) / 100,
          status: 'success',
          refundTransactionId: `${createdTime.getFullYear()}${String(createdTime.getMonth() + 1).padStart(2, '0')}${String(createdTime.getDate()).padStart(2, '0')}${String(getRandomNumber(100000000, 999999999))}`,
          paymentMethod: ['alipay', 'wechat', 'bank'][Math.floor(Math.random() * 3)],
          timestamp: createdTime.toISOString(),
          signature: 'sha256_signature_here'
        }

    const requestHeaders = {
      'Content-Type': 'application/json',
      'X-Signature': `sha256=${getRandomNumber(100000, 999999)}...`,
      'User-Agent': callbackType === 'webhook' ? 'AnyPay-Webhook/1.0' : 'AnyPay-Callback/1.0'
    }

    const callback: MerchantCallback = {
      id: `MC${createdTime.getFullYear()}${String(createdTime.getMonth() + 1).padStart(2, '0')}${String(createdTime.getDate()).padStart(2, '0')}${String(i).padStart(6, '0')}`,
      orderId,
      orderType,
      merchantId,
      merchantName: `商户${i}`,
      callbackUrl: `https://merchant${i}.example.com/callback/${orderType}`,
      callbackType,
      status,
      requestHeaders: JSON.stringify(requestHeaders, null, 2),
      requestBody: JSON.stringify(requestData, null, 2),
      retryCount,
      maxRetryCount: 5,
      createTime: createdTime.toLocaleString(),
      updateTime: updatedTime.toLocaleString(),
      remark: `${orderType === 'payment' ? '支付' : '退款'}${status === 'success' ? '成功' : '失败'}回调`
    }

    if (status === 'success') {
      callback.responseBody = JSON.stringify({
        code: 200,
        message: 'success',
        received: true
      }, null, 2)
      callback.responseCode = 200
      callback.responseHeaders = JSON.stringify({
        'Content-Type': 'application/json',
        'Server': ['nginx/1.18.0', 'Apache/2.4.41', 'IIS/10.0'][Math.floor(Math.random() * 3)]
      }, null, 2)
      callback.callbackTime = updatedTime.toLocaleString()
    } else if (status === 'failed') {
      callback.responseCode = getRandomNumber(400, 500)
      callback.responseHeaders = JSON.stringify({
        'Content-Type': getRandomNumber(1, 2) === 1 ? 'application/json' : 'text/html',
        'Server': ['nginx/1.18.0', 'Apache/2.4.41', 'IIS/10.0'][Math.floor(Math.random() * 3)]
      }, null, 2)
      callback.callbackTime = updatedTime.toLocaleString()

      const errorMessages = [
        '商户服务器内部错误',
        '回调URL无法访问',
        '签名验证失败',
        '请求超时',
        '服务暂时不可用'
      ]
      callback.errorMessage = errorMessages[Math.floor(Math.random() * errorMessages.length)]

      if (retryCount < 5) {
        const nextRetry = new Date(updatedTime.getTime() + Math.pow(2, retryCount) * 60 * 1000) // 指数退避重试
        callback.nextRetryTime = nextRetry.toLocaleString()
      }
    } else if (status === 'timeout') {
      callback.callbackTime = updatedTime.toLocaleString()
      callback.errorMessage = '回调请求超时'
      if (retryCount < 5) {
        const nextRetry = new Date(updatedTime.getTime() + Math.pow(2, retryCount) * 60 * 1000) // 指数退避重试
        callback.nextRetryTime = nextRetry.toLocaleString()
      }
    }

    data.push(callback)
  }

  return data
}

export const mockData = generateMockData()

// 增删改查
export function addMerchantCallback(item: MerchantCallback) {
  mockData.unshift(item)
}

export function updateMerchantCallback(id: string, item: Partial<MerchantCallback>) {
  const idx = mockData.findIndex(m => m.id === id)
  if (idx > -1) Object.assign(mockData[idx], item)
}

export function deleteMerchantCallback(id: string) {
  const idx = mockData.findIndex(m => m.id === id)
  if (idx > -1) mockData.splice(idx, 1)
}

export function getMerchantCallback(id: string): MerchantCallback | undefined {
  return mockData.find(m => m.id === id)
}

// 状态映射
export const statusMap = {
  pending: { text: '待回调', color: 'orange' },
  success: { text: '回调成功', color: 'success' },
  failed: { text: '回调失败', color: 'error' },
  timeout: { text: '回调超时', color: 'warning' }
}

// 订单类型映射
export const orderTypeMap = {
  payment: { text: '支付订单', color: 'blue' },
  refund: { text: '退款订单', color: 'red' }
}

// 回调类型映射
export const callbackTypeMap = {
  webhook: { text: 'Webhook', color: 'green' },
  http_post: { text: 'HTTP POST', color: 'purple' }
}